package com.wits.qso.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.UserType;
import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Aid;
import com.wits.qso.entity.Attachment;
import com.wits.qso.entity.Teacher;
import com.wits.qso.service.AidService;
import com.wits.qso.service.AttachmentService;
import com.wits.qso.service.TeacherService;

@Controller
@RequestMapping(value = "qso/aid")
public class AidController extends BaseController {
	List<Attachment> resultList=new ArrayList<Attachment>();
	/**
	 * 注入aidService
	 */
	@Autowired
	private AidService aidService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private TeacherService teacherService;
	
	@RequestMapping(value="/toList")
	public String toList(){
		return "qso/aid/list";
	}
	
	/**
	 * 加载课件信息列表
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public String list(Model model,@ModelAttribute("page") PageParam page, HttpServletRequest req){
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
		Page<Aid> listPage = aidService.findPage(Aid.class, searchParams, page);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return PageUtil.toAjaxPageResult(listPage.getTotalElements(), listPage.getContent());
	}
	
	/**
	 * 课件列表上按钮的触发事件处理
	 * @param model
	 * @param viewType
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/view/{viewType}")
	public String toView(Model model,@PathVariable String viewType,@RequestParam String id){
		if(ViewType.Add.getView().equals(viewType)){
			Teacher tea=null;
			if((UserType.TEACHER.getValue()).equals(getCurrentUser().getUserType())){
				tea=teacherService.findByUserId(getCurrentUserId());
			}else{
				tea = new Teacher();
			}

			Aid aid=new Aid();
			aid.setTeaid(tea);
			model.addAttribute(WebConstants.COMMAND,aid );
			model.addAttribute("attachments",null);
		}else{
			Aid aid=aidService.getOne(id);
			List<Attachment> attachments=attachmentService.findByBusinessIdAndType(aid.getId(), "qso_aid");
			model.addAttribute(WebConstants.COMMAND, aid);
			if(attachments==null || attachments.size()==0)
			model.addAttribute("attachments",null);
			else
			model.addAttribute("attachments",attachments);
		}
		
		model.addAttribute("viewType", viewType);
		return "qso/aid/form";
	}
	
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public Object save(Model model,
			@ModelAttribute("command") @Valid Aid command,@RequestParam String terid,
			@RequestParam String viewType,
			BindingResult result,
			HttpServletRequest req){
		if(result.hasErrors()){
			model.addAttribute(WebConstants.COMMAND, command);
			return toView(model, viewType, command.getId());
		}
		if(ViewType.Add.getView().equals(viewType)){
			command.setDateCre(new Date());
			command.setUserCre(getCurrentUserId());
		}else{
			command.setDateUpd(new Date());
			command.setUserUpd(getCurrentUserId());
		}
		try {
			command.setTeaid(teacherService.getOne(terid));
			Aid temp= aidService.save(command);
			List<Attachment> tempList=new ArrayList<Attachment>();
			for (int i = 0; i < resultList.size(); i++) {
				Attachment ata = resultList.get(i);
				ata.setUserCre(getCurrentUserId());
				ata.setBusinessId(temp.getId());
				ata.setBusinessType("qso_aid");
				attachmentService.save(ata);
			}
			
			return ajaxDoneSuccess(this.getText("save.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("save.failed"), e);
		}
	}
	
	/**
	 * 
	 *方法摘要：文件上传
	 *@param
	 *@return String
	 */
	@RequestMapping(value="/uploadFile",method=RequestMethod.POST)
	public void uploadFile(MultipartHttpServletRequest request,ModelMap modelMap){
		String realPath = request.getRealPath("/upload");
		resultList = aidService.addFile(realPath, request.getFiles("file"));
		for (int i = 0; i < resultList.size(); i++) {
			attachmentService.save(resultList.get(i));
		}
	}
	
	/**
	 * 删除文件
	 * @param request
	 * @param modelMap
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/deleteFile")
	@ResponseBody
	public Object deleteFile(HttpServletRequest request,ModelMap modelMap,@RequestParam String id){
		String realPath = request.getRealPath("/upload");
		Attachment atta=attachmentService.getOne(id);
		if(attachmentService.deleteById(id)>0){
			File file=new File(realPath+"/"+atta.getOriginalName());
			file.delete();
		}
		return "true";
        
	}
	
	/**
	 * 
	 *方法摘要：文件下载
	 *@param
	 *@return String
	 */
	@RequestMapping(value="/downloadFile")
	public void downloadFile(HttpServletRequest request,HttpServletResponse response,@RequestParam String id){
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String realPath = request.getRealPath("/upload");
		Attachment attachment=attachmentService.getOne(id);
		response.setHeader("Content-Disposition", "attachment;fileName="+attachment.getOriginalName());
		try {
			String fileName = realPath + "\\" + attachment.getOriginalName();
			File file=new File(fileName);
			System.out.println(file.getAbsolutePath());
			InputStream inputStream=new FileInputStream(file);
			OutputStream os=response.getOutputStream();
			byte[] b=new byte[1024];
			int length;
			while((length=inputStream.read(b))>0){
				os.write(b,0,length);
			}
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 删除课件信息
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids){
		try {
			aidService.deleteInBatch(Arrays.asList(StringUtil.split(ids, ",")));
			return ajaxDoneSuccess(this.getText("delete.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("delete.failed"));
		}
	}
	
	/**
	 * 唯一键检查
	 * @param id
	 * @param oldId
	 * @return
	 */
	@RequestMapping(value="/checkUniqueId")
	@ResponseBody
	public boolean checkUniqueId(@RequestParam("id") String id,@RequestParam("oldId") String oldId){
		if(id.equals(oldId)){
			return true;
		}
		Aid obj=aidService.getOne(id);
		return obj == null;
	}
}
